package com.lap.context.starter.core.interceptor;

import com.lap.context.starter.shared.HeaderUtil;
import com.lap.framework.common.constant.Header;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class FeignInterceptor implements RequestInterceptor {

  @Override
  public void apply(RequestTemplate template) {
    ServletRequestAttributes attributes =
        (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    assert attributes != null;
    HttpServletRequest request = attributes.getRequest();
    Integer userId = HeaderUtil.getUserId(request);
    if (userId != null) {
      template.header(Header.USER_ID, String.valueOf(userId));
      template.header(Header.USER_NAME, HeaderUtil.getUserName(request));
      template.header(Header.FULL_NAME, HeaderUtil.getFullName(request));
    }
    template.header(Header.REQUEST_ID, request.getHeader(Header.REQUEST_ID));
  }
}
